package com.bw.controller.customer;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.bw.entity.customer.PiCustomer;
import com.bw.entity.dc.PiLinkman;
import com.bw.resp.ResponseResult;
import com.bw.service.customer.IPiCustomerService;
import com.bw.req.TbCostomer;
import com.bw.service.dc.IPiLinkmanService;
import com.bw.utils.ReadExcel;
import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wsq
 * @since 2020-06-16
 */
@RestController
@RequestMapping("customer")
public class PiCustomerController {
    @Resource
    private IPiCustomerService iPiCustomerService;

    @Resource
    private IPiLinkmanService linkmanService;
    private final Logger logger= LoggerFactory.getLogger(PiCustomerController.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IPiLinkmanService iPiLinkmanService;

    @Autowired
    private StringRedisTemplate redis;

    /**
     * 根据会话id查询当前客户
     * @param id
     * @return
     */
    @PostMapping("/getcostomer/{id}")
    public ResponseResult getcostomer(@PathVariable("id") String id) {
        logger.info("根据当前登录id查询当前客户执行开始");
        ResponseResult re = new ResponseResult(false, 400, "发送失败");
        try {
          PiCustomer byId = iPiCustomerService.getById(id);
            re.setResult(byId);
            logger.info("根据当前登录id查询当前客户执行结束");
            return re;
        } catch (Exception e) {
            logger.error("根据当前登录id查询当前客户执行,{}",e.toString());
            return re;
        }
    }
    /**
     * 根据会话id查询当前联系人
     * @param id
     * @return
     */
    @PostMapping("/getlinkman/{id}")
    public ResponseResult getlinkman(@PathVariable("id") String id) {
        logger.info("根据当前登录id查询当前联系人执行开始");
        ResponseResult re = new ResponseResult(false, 400, "发送失败");
        try {
           PiLinkman byId = linkmanService.getById(id);
           re.setResult(byId);
           re.setResult(byId);
            logger.info("根据当前登录id查询当前联系人结束");
            return re;
        } catch (Exception e) {
            logger.error("根据当前登录id查询当前联系人执行,{}",e.toString());
            return re;
        }
    }

    /**
     * 发送验证码
     * @param tel
     * @return
     */
    @PostMapping("/sendYZM/{tel}")
    public ResponseResult sendYZM(@PathVariable("tel") String tel) {
        logger.info("调用发送验证码方法执行开始");
        ResponseResult re = new ResponseResult(false, 400, "发送失败");
        try {
            re=iPiCustomerService.sendYzm(tel);
            logger.info("调用发送验证码方法执行结束");
            return re;
        } catch (Exception e) {
            logger.error("调用发送验证码方法执行,{}",e.toString());
            return re;
        }
    }

    //客户登录的方法
    @PostMapping("/clogin")
    public ResponseResult clogin(@RequestBody TbCostomer costomer) {
        ResponseResult re = new ResponseResult(false, 400, "验证失败");
        logger.info("验证码登录执行开始");
        try {
            QueryWrapper qw = new QueryWrapper();
            if(costomer.getTel()!=null) {
                qw.eq("tel", costomer.getTel());
            }
            List<PiLinkman> linkmenlist=linkmanService.list(qw);
            PiLinkman linkman = linkmenlist.get(0);
            String code = redis.boundValueOps("yzm"+linkman.getTel()).get();
            if(code==null) {
                re.setSuccess(false);
                re.setCode(400);
                re.setMessage("验证码失效");
                logger.info("验证码失效");
                return re;
            }
            if(!code.equals(costomer.getYzm())) {
                re.setSuccess(false);
                re.setCode(400);
                re.setMessage("验证码错误");
                logger.info("验证码错误");
                return re;
            }
            //获取客户信息
            QueryWrapper qw2 = new QueryWrapper();
            if(linkman.getCustomerId()!=null) {
                qw2.eq("id", linkman.getCustomerId());
            }
            List<PiCustomer> clist=iPiCustomerService.list(qw2);
            PiCustomer byId = clist.get(0);
            //生成令牌登录
            // PrivateKey privateKey = RsaUtils.getPrivateKey("E:\\1711A\\ras.pri");
            //PrivateKey privateKey= RsaUtils.getPrivateKey("E:\\1711A\\rea.pri");
            PrivateKey privateKey= RsaUtils.getPrivateKey("E:\\1711A\\keys\\rea.pri");
            UserInfo userInfo = new UserInfo(costomer.getId(), costomer.getName());
            String token = JwtUtils.generateToken(userInfo, privateKey, 30);
            Map<Object, Object> map2 = new HashMap<>();
            map2.put("costomer", byId);
            map2.put("token", token);
            map2.put("linkman", linkman);
            re.setResult(map2);
            re.setCode(200);
            re.setSuccess(true);
            re.setMessage("验证成功");
            logger.info("验证码登录执行结束");
            return re;
        } catch (Exception e) {
            logger.error("验证码登录执行失败,{}",e.toString());
            return re;
        }

    }
    /**
     *
     * 客户列表
     */
    @PostMapping("list/{pagenum}/{pagesize}")
    public ResponseResult list(@PathVariable("pagenum") int pagenum, @PathVariable("pagesize") int pagesize, @RequestBody PiCustomer piCustomer) { //参数json字符串
        logger.info("客户列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(pagenum,pagesize);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("isdelete",0);
           if (piCustomer.getName()!=null) {
                queryWrapper.like("name","%" + piCustomer.getName() + "%");
            }

            List<PiCustomer> list = iPiCustomerService.list(queryWrapper);
            PageInfo pageInfo = new PageInfo(list);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
            result.setSuccess(true);
        } catch (Exception e) {
            logger.error("查询失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
            System.out.println(e.toString());
        }
        logger.info("客户列表查询结束");
        return result;
    }
    /**
     * 客户添加
     */
    @PostMapping("save")
    public ResponseResult save(@RequestBody PiCustomer piCustomer) {
        logger.info("客户添加");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            piCustomer.setIsdelete(0);
            iPiCustomerService.saveOrUpdate(piCustomer);//添加
            result.setMessage("保存成功");
        } catch (Exception e) {
            logger.error("客户添加保存失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("保存失败:" + e.toString());
        }
        logger.info("客户添加结束");
        return result;
    }
    /**
     * 客户删除(需要逻辑删除)
     */
    @DeleteMapping("del/{id}")
    public ResponseResult delTree(@PathVariable("id") BigInteger id) {
        logger.info("客户删除(需要逻辑删除)");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiCustomer byId = iPiCustomerService.getById(id);
            byId.setIsdelete(1);
            iPiCustomerService.saveOrUpdate(byId);//修改删除状态为1，已删除
            result.setMessage("删除成功");
        } catch (Exception e) {
            logger.error("客户删除(需要逻辑删除)失败",e.toString());
            result.setSuccess(false);
            result.setMessage("删除失败:" + e.toString());
        }
        logger.info("客户删除结束(需要逻辑删除)");
        return result;
    }
    /**
     * 客户回显
     */
    @GetMapping("get/{id}")
    public ResponseResult get(@PathVariable("id") BigInteger id) {
        logger.info("客户回显");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiCustomer byId = iPiCustomerService.getById(id);//根据id回显
            result.setResult(byId);
        } catch (Exception e) {
            logger.error("客户回显失败",e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("客户回显结束");
        return result;
    }
    /**
     * @Description:下拉框查询
     * @Author: 李钊毅
     * @Date: 2020/6/17 19:36
     * @return: com.bw.resp.ResponseResult
     **/
    @GetMapping("getCustom")
    public ResponseResult getCustom() {
        logger.info("联系人添加时查看客户下拉框");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            result.setResult(iPiCustomerService.list());
        } catch (Exception e) {
            logger.info("联系人添加时查看客户下拉框失败",e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("联系人添加时查看客户下拉框结束");
        return result;
    }
    /**
     * 文件导入
     *
     * @param file
     * @return
     */
    @PostMapping("/imporExcel")
    public ResponseResult imporExcel(MultipartFile file) {
        logger.info("文件导入");
        ResponseResult re = new ResponseResult(false, 400, "上传失败");
        try {
            //获取后缀
            String hou = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'), file.getOriginalFilename().length());
            InputStream in = file.getInputStream();
            //调用封装工具类，处理数据
            List<Map> readExcel = ReadExcel.readExcel(hou, in);
            String jsonString = JSON.toJSONString(readExcel);//转成string
            System.out.println(jsonString);
            List<PiCustomer> plist = JSON.parseArray(jsonString, PiCustomer.class);//转成对象集合
            //保存
            iPiCustomerService.saveBatch(plist);
            re.setSuccess(true);
            re.setMessage("上传成功");
            logger.info("文件导入结束");
            return re;
        } catch (Exception e) {
            logger.info("文件导入失败",e.toString());
            return re;
        }

    }
    /**
     * excel导出
     */
    @GetMapping("exportExcle")
    public void exportExcle(HttpServletResponse response) throws Exception {
        logger.info("excel导出");
        List<PiCustomer> list = iPiCustomerService.list();//获取用户列表数据
        response.setHeader("Content-Type","application/vnd.ms-exce1;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("客户管理".getBytes(),"iso-8859-1")+".xls");

        //获取excle模板的流
        ClassPathResource classPathResource=new ClassPathResource("xls/customer.xls");///定位到具体的资源
        InputStream inputStream = classPathResource.getInputStream();//获取exce1模板的输入流
        ExcelUtils.addValue("list",list);
        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数：模板流，第三个参数:输出到哪
        logger.info("excel导出结束");
    }



}
